<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="顾客ID" prop="guestId">
        <el-input
          v-model="queryParams.guestId"
          placeholder="请输入顾客ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in wdm_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['ruoyi:address:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ruoyi:address:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ruoyi:address:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['ruoyi:address:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="addressList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="序号"
        type="index"
        width="60px"
        align="center"
        prop="addressId"
      />
      <el-table-column label="顾客ID" align="center" prop="guestId" />
      <el-table-column label="收货人" align="center" prop="deliveryName" />
      <el-table-column label="联系电话" align="center" prop="deliveryPhone" />
      <el-table-column label="省份" align="center" prop="province" />
      <el-table-column label="城市" align="center" prop="city" />
      <el-table-column label="区县" align="center" prop="district" />
      <el-table-column label="详细地址" align="center" prop="detailAddress" />
      <el-table-column label="邮政编码" align="center" prop="postalCode" />
      <el-table-column label="是否默认" align="center" prop="isDefault">
        <template #default="scope">
          <dict-tag :options="is_default" :value="scope.row.isDefault" />
        </template>
      </el-table-column>
      <el-table-column label="地址标签" align="center" prop="addressTag">
        <template #default="scope">
          <dict-tag :options="address_tag" :value="scope.row.addressTag" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="wdm_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="remark" />
      <el-table-column
        label="操作"
        width="200px"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ruoyi:address:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ruoyi:address:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改收货地址信息对话框 -->
    <el-dialog :title="title" v-model="open" width="50%" append-to-body>
      <el-form
        ref="addressRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-card class="box-card">
          <div class="clearfix" style="text-align: center">
            <span style="font-size: 20px; color: #1890ff"
              >收货地址基本信息</span
            >
          </div>

          <el-row :gutter="24" class="mb8">
            <el-col :span="12">
              <!-- <el-form-item label="顾客ID" prop="guestId">
                <el-input v-model="form.guestId" placeholder="请输入顾客ID" />
              </el-form-item> -->
              <el-form-item label="顾客ID" prop="guestId">
                <el-input
                  v-model="form.guestId"
                  placeholder="点击选择顾客"
                  readonly
                  @click="openGuestSelector"
                >
                  <template #append>
                    <el-button icon="Search" @click="openGuestSelector" />
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="收货人姓名" prop="deliveryName">
                <el-input
                  v-model="form.deliveryName"
                  placeholder="请输入收货人姓名"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24" class="mb8">
            <el-col :span="12">
              <el-form-item label="联系电话" prop="deliveryPhone">
                <el-input
                  v-model="form.deliveryPhone"
                  placeholder="请输入收货人联系电话"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮政编码" prop="postalCode">
                <el-input
                  v-model="form.postalCode"
                  placeholder="请输入邮政编码"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24" class="mb8">
            <el-col :span="12">
              <el-form-item label="省份" prop="province">
                <el-input v-model="form.province" placeholder="请输入省份" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="城市" prop="city">
                <el-input v-model="form.city" placeholder="请输入城市" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="区县" prop="district">
                <el-input v-model="form.district" placeholder="请输入区县" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="详细街道地址" prop="detailAddress">
            <el-input
              v-model="form.detailAddress"
              placeholder="请输入详细街道地址"
            />
          </el-form-item>

          <el-row :gutter="24" class="mb8">
            <el-col :span="12">
              <el-form-item label="是否默认" prop="isDefault">
                <el-select
                  v-model="form.isDefault"
                  placeholder="请选择是否默认"
                >
                  <el-option
                    v-for="dict in is_default"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地址标签" prop="addressTag">
                <el-select
                  v-model="form.addressTag"
                  placeholder="请选择地址标签"
                >
                  <el-option
                    v-for="dict in address_tag"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in wdm_status"
                :key="dict.value"
                :label="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item label="删除" prop="delFlag">
            <el-radio-group v-model="form.delFlag">
              <el-radio
                v-for="dict in del_flag"
                :key="dict.value"
                :label="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <!-- 添加按钮 -->
          <el-button @click="showGuestDetail(row)">查看详情</el-button>
        </el-card>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 顾客信息 -->
    <!-- <guestInfoList ref="guestInfoList" :query="query" @refresh="getList" />" -->
    <!-- 在父组件中使用 -->

    <!-- 顾客选择对话框 -->
    <el-dialog
      v-model="guestSelectorVisible"
      title="选择顾客"
      width="80%"
      append-to-body
      @opened="loadGuestList"
    >
      <!-- 顾客列表表格 -->
      <el-table
        v-loading="guestSelectorLoading"
        height="30vh"
        :data="guestList"
        @selection-change="handleGuestSelection"
      >
        <el-table-column v-if="guestList.length === 0">
          <template #default>
            <div style="text-align: center; padding: 20px">暂无数据</div>
          </template>
        </el-table-column>

        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="顾客ID" align="center" prop="guestId" />
        <el-table-column label="用户名" align="center" prop="username" />
        <el-table-column label="昵称" align="center" prop="nickname" />
        <el-table-column label="手机号" align="center" prop="mobile" />
        <el-table-column label="顾客类型" align="center" prop="guestType">
          <template #default="scope">
            <dict-tag :options="guest_type" :value="scope.row.guestType" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="wdm_status" :value="scope.row.status" />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="guestTotal > 0"
        :total="guestTotal"
        v-model:page="guestQueryParams.pageNum"
        v-model:limit="guestQueryParams.pageSize"
        @pagination="loadGuestList"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="guestSelectorVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmGuestSelection"
            >确 定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Address">
import guestInfoList from "@/views/components/guestInfoList";
// 在顶部导入顾客接口
import { listGuest } from "@/api/ruoyi/guest";
import { ref, reactive, getCurrentInstance, toRefs } from "vue";

import {
  listAddress,
  getAddress,
  delAddress,
  addAddress,
  updateAddress,
} from "@/api/ruoyi/address";

const { proxy } = getCurrentInstance();
const { wdm_status, is_default, address_tag, del_flag } = proxy.useDict(
  "wdm_status",
  "is_default",
  "address_tag",
  "del_flag"
);

const addressList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    guestId: null,
    status: null,
  },
  rules: {
    guestId: [{ required: true, message: "顾客ID不能为空", trigger: "blur" }],
    deliveryName: [
      { required: true, message: "收货人姓名不能为空", trigger: "blur" },
    ],
    deliveryPhone: [
      { required: true, message: "收货人联系电话不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

// ===============================================

// 在 <script setup> 中添加以下代码
const guestSelectorVisible = ref(false);
const guestSelectorLoading = ref(false);
const guestList = ref([]);
const selectedGuest = ref(null);

// 新增状态变量
const guestQueryParams = ref({ pageNum: 1, pageSize: 10 });
const guestTotal = ref(0);

// =============================================================================

// 顾客加载方法
function loadGuestList() {
  guestSelectorLoading.value = true;

  listGuest(guestQueryParams.value)
    .then((response) => {
      // 详细日志用于调试
      console.log("完整响应:", response);

      // 确保访问正确的数据路径
      let rows = [];
      if (Array.isArray(response.rows)) {
        rows = response.rows;
      } else if (response.data && Array.isArray(response.data.rows)) {
        rows = response.data.rows;
      }

      console.log("实际数据数组:", rows);
      console.log("数据条数:", rows.length);

      guestList.value = rows;
      guestTotal.value = response.total || response.data?.total || 0;

      guestSelectorLoading.value = false;
    })
    .catch((error) => {
      console.error("加载顾客列表失败:", error);
      proxy.$modal.msgError("加载顾客列表失败，请稍后重试");
      guestSelectorLoading.value = false;
    });
}

/** 打开顾客选择器 */
function openGuestSelector() {
  guestSelectorVisible.value = true;
  // 重置查询参数
  guestQueryParams.value = {
    pageNum: 1,
    pageSize: 10,
    status: "0", // 默认只查询启用状态的顾客
  };
  // loadGuestList();
}

// 分页处理函数
function handleGuestPagination(pagination) {
  guestQueryParams.pageNum = pagination.page;
  guestQueryParams.pageSize = pagination.limit;
  // loadGuestList(); // 分页变化时重新加载数据
}

// function openGuestSelector() {
//   guestSelectorVisible.value = true;
//   guestQueryParams.value = { pageNum: 1, pageSize: 10 };
//   loadGuestList();
// }

// 处理顾客选择
function handleGuestSelection(selection) {
  // 单选模式，只允许选择一条记录
  if (selection.length > 0) {
    selectedGuest.value = selection[selection.length - 1];
  } else {
    selectedGuest.value = null;
  }
}

// 确认选择
function confirmGuestSelection() {
  if (!selectedGuest.value) {
    proxy.$modal.msgWarning("请选择一位顾客");
    return;
  }

  // 将选中的顾客ID赋值到输入框
  form.value.guestId = selectedGuest.value.guestId;

  // 关闭对话框
  guestSelectorVisible.value = false;
}

// =============================================================================

/** 查询收货地址信息列表 */
function getList() {
  loading.value = true;
  listAddress(queryParams.value).then((response) => {
    // addressList.value = response.rows;
    // 过滤已删除数据（假设 delFlag 字段标识删除状态）
    addressList.value = response.rows.filter(
      (item) => item.delFlag !== "2"
    );
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    addressId: null,
    guestId: null,
    deliveryName: null,
    deliveryPhone: null,
    province: null,
    city: null,
    district: null,
    detailAddress: null,
    postalCode: null,
    isDefault: null,
    addressTag: null,
    status: null,
    delFlag: null,
    version: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
  };
  proxy.resetForm("addressRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.addressId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加收货地址信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _addressId = row.addressId || ids.value;
  getAddress(_addressId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改收货地址信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["addressRef"].validate((valid) => {
    if (valid) {
      if (form.value.addressId != null) {
        updateAddress(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addAddress(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _addressIds = row.addressId || ids.value;
  proxy.$modal
    .confirm('是否确认删除收货地址信息编号为"' + _addressIds + '"的数据项？')
    .then(function () {
      return delAddress(_addressIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "ruoyi/address/export",
    {
      ...queryParams.value,
    },
    `address_${new Date().getTime()}.xlsx`
  );
}

// 函数加载
getList();

loadGuestList();
</script>
